
package atm.components;

import java.util.Scanner;

import atm.model.CreditCardInfo;
import atm.utilities.ValidationUtilities;

/**
 * Reads inserted credit cards and provides basic input validation.
 */
public class CreditCardReader {

	/**
	 * Attempts to read credit card given amount of time.
	 * 
	 * @param attempts
	 *            Number of read attempts before give up
	 * @return An object representing Credit Card information or null if failed to read credit card
	 */
	public CreditCardInfo readCreditCard(int attempts) {
		if (attempts > 0) {

			@SuppressWarnings("resource")
            Scanner scanner = new Scanner(System.in);

			String tempCreditCardNumber = null;
			String tempMonth = null;
			String tempYear = null;

			int attemptNumber = 0;

			boolean readSuccessfully = false;

			try {
				do {
					System.out.printf(">> CreditCardReader: Reading credit card in progres... Attempt %1$s" + "\r\n", ++attemptNumber);
					System.out.print(">> CreditCardReader: Credit card number: ");
					tempCreditCardNumber = scanner.nextLine();
					System.out.print(">> CreditCardReader: Valid through months: ");
					tempMonth = scanner.nextLine();
					System.out.print(">> CreditCardReader: Valid through years: ");
					tempYear = scanner.nextLine();
					--attempts;

					if (ValidationUtilities.isCreditCardNumber(tempCreditCardNumber) && ValidationUtilities.isMonthNumber(tempMonth)
					        && ValidationUtilities.isYearNumber(tempYear)) {
						readSuccessfully = true;
					}
				} while (attempts > 0 && !readSuccessfully);
			} finally {
				if (scanner != null) {
					
				}
			}

			return readSuccessfully ? new CreditCardInfo(tempCreditCardNumber, Integer.parseInt(tempMonth), Integer.parseInt(tempYear))
			        : null;
		}
		throw new RuntimeException();
	}

}
